﻿using System;
using System.Collections.Generic;
using System.Text;
using AMS.DataAccess.BO;
using AMS.DataAccess.Common;
using System.Diagnostics;
using System.Data;
using AMS.DataAccess.Interfaces;

namespace AMS.DataAccess.Sql
{
    public class UserManager : IUserManager
    {
        private const string UserTableName = "TS_User";

        /// <summary>
        /// Returns the new id
        /// </summary>
        /// <param name="user"></param>
        public void AddUser(CallContext context, UserInfo user)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user cannot be null");
            }

            SqlInsert sqlInsert = new SqlInsert(UserTableName);
            sqlInsert.AddBusinessObject(user);
            sqlInsert.Add("SELECT @@identity");
#if SHOW_SQL
            Debug.WriteLine(sqlInsert.ToString());
#endif
            DataSet ds = SqlDBHelper.Query(sqlInsert.ToString());
            user.AID = AdoConverter.ToInt32(ds.Tables[0].Rows[0][0]);
        }

        /// <summary>
        /// Update user info
        /// </summary>
        /// <param name="user"></param>
        public bool UpdateUser(CallContext context, UserInfo user)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user cannot be null");
            }

            SqlUpdate sqlUpdate = new SqlUpdate(UserTableName);
            sqlUpdate.AddBusinessObject(user);
#if SHOW_SQL
            Debug.WriteLine(sqlUpdate.ToString());
#endif
            return (0 < SqlDBHelper.ExecuteSql(sqlUpdate.ToString()));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public bool DeleteUser(CallContext context, int userId)
        {
            SqlDelete sqlDelete = new SqlDelete(UserTableName);
            sqlDelete.AddCondition(new SqlCondition("AID", userId));
#if SHOW_SQL
            Debug.WriteLine(sqlDelete.ToString());
#endif
            return (0 < SqlDBHelper.ExecuteSql(sqlDelete.ToString()));
        }
    }
}
